<?php
/**
 * 订单批量导入导出功能
 *
 * @author Administrator
 *
 */
class CSVService {
	
	private $_tempName = 'file_upload'; //上传文件名
	private $_fileTypes = array ('csv' ); // File extensions
	private $_targetFolder = '/static/attached/csv'; // Relative to the root
	

	private $_status = array (0 => "等待审核", "1" => "通过", "-1" => "不通过" );
	
	/**
	 * 
	 * 导入数据
	 * @param String $timestamp
	 * @param String $token
	 * @param array $user
	 */
	public function import($timestamp, $token, $user) {
		
		if (! $this->checkValidate ( $_POST ['codeimg'] )) {
			return "验证码错误";
		}
		
		$filename = $this->upload ( $timestamp, $token );
		if (! $filename) {
			return "文件类型不符合";
		}
		$filename = getcwd () . $filename;
		
		if (! file_exists ( $filename )) {
			echo "文件名不正确，应该是CSV文件，而不是xls文件";
			exit ();
		}
		
		$this->parseCSV ( $filename, $user );
		unlink ( $filename );
		return "succss";
	}
	
	/**
	 * 检测验证码是否正确
	 */
	private function checkValidate($codeimg) {
		if (! isset ( $codeimg )) {
			return false;
		}
		if (trim ( $codeimg ) != $_SESSION ["authnum_session"]) {
			return false;
		}
		return true;
	}
	
	public function upload() {
		if (is_uploaded_file ( $_FILES [$this->_tempName] ['tmp_name'] )) {
			$upfile = $_FILES [$this->_tempName];
			$name = $upfile [name];
			$type = $upfile [type];
			$size = $upfile [size];
			$tmp_name = $upfile [tmp_name];
			$error = $upfile [error];
			$fileType = substr ( $name, strpos ( $name, "." ) + 1 );
			switch ($fileType) {
				case 'csv' :
					$ok = 1;
					break;
			}
			if ($ok == '1' && $error == '0') {
				$fileType = substr ( $name, strpos ( $name, "." ) + 1 );
				$newName = time () . "." . $fileType;
				$filepath = "/static/attached/csv";
				/*
                if (! is_dir($dir)) {
                    mkdir($filepath);
                }
                */
				$filepath = $filepath . DIRECTORY_SEPARATOR . $newName;
				move_uploaded_file ( $tmp_name, getcwd () . $filepath );
				return $filepath;
			
			}
			return "文件名不正确，应该是CSV文件，而不是xls文件";
		
		}
	}
	
	/**
	 * 解析CSV文件   
	 * 注意文件处理的大小
	 */
	public function parseCSV($filename, $user) {
		
		$handle = fopen ( $filename, 'r' );
		$result = $this->input_csv ( $handle ); //解析csv 
		$len_result = count ( $result );
		if ($len_result == 0) {
			return '没有任何数据！';
		}
		
		$notMatchFile = "";
		$line = "";
		$time = time ();
		//第一行去掉    军区 区域  业务经理 客户名称 客户手机 定金金额  客户地址
		for($i = 1; $i < $len_result; $i ++) { //循环获取各字段值 
			

			$param ['junqu'] = iconv ( 'gb2312', 'utf-8', $result [$i] [0] ); //中文转码 
			$param ['area'] = iconv ( 'gb2312', 'utf-8', $result [$i] [1] ); //中文转码 
			

			$param ['man'] = iconv ( 'gb2312', 'utf-8', $result [$i] [2] ); //中文转码 
			$param ['customer'] = iconv ( 'gb2312', 'utf-8', $result [$i] [3] ); //中文转码 
			$param ['mobile_phone'] = $result [$i] [4]; //中文转码 
			

			$param ['money'] = $result [$i] [5]; //中文转码 
			$param ['address'] = iconv ( 'gb2312', 'utf-8', $result [$i] [6] ); //中文转码 
			$param ['add_time'] = $time;
			
			$param ['uid'] = $user ['uid'];
			$param ['jxs'] = $user ['realname'];
			$this->addData ( $param );
		}
		
		//	$data_values = substr ( $data_values, 0, - 1 ); //去掉最后一个逗号 
		fclose ( $handle ); //关闭指针 
	

	}
	/**
	 * 过滤
	 * Enter description here ...
	 */
	private function filter($line) {
	
	}
	
	private function addData($param) {
		
		CSVModel::instance ()->addOrder ( $param );
	}
	
	private function input_csv($handle) {
		$out = array ();
		$n = 0;
		while ( $data = fgetcsv ( $handle, 10000 ) ) {
			$num = count ( $data );
			for($i = 0; $i < $num; $i ++) {
				$out [$n] [$i] = $data [$i];
			}
			$n ++;
		}
		return $out;
	}
	private function setCsvHeader() {
		header ( "Cache-Control: public" );
		header ( "Pragma: public" );
		header ( "Content-type:application/vnd.ms-excel" );
		$file = date ( "md", time () );
		header ( "Content-Disposition:attachment;filename=$file.csv" );
	}
	/**
	 * 统计
	 */
	public function stats($uid) {
		
		$total = CSVModel::instance ()->countNum ( array ('uid' => $uid ) );
		$pass = CSVModel::instance ()->countNum ( array ('uid' => $uid, 'status' => 1 ) );
		
		$rs = CSVModel::instance ()->top ();
		foreach ( $rs as $k => $v ) {
			if ($v ['uid'] == $uid) {
				$rank = $k;
				break;
			}
		}
		return array ('total' => $total, 'pass' => $pass, 'rank' => $rank + 1 );
	
	}
	/**
	 * 导出
	 * Enter description here ...
	 */
	public function export($uid) {
		$this->setCsvHeader ();
		$rs = CSVModel::instance ()->getCSV ( array ('uid' => $uid ) );
		echo "时间,军区,区域,业务经理,客户名称,客户手机,定金金额,审核状态\n";
		$format = "%s,%s,%s,%s,%s,%s,%s,%s\n";
		foreach ( $rs as $v ) {
			echo sprintf ( $format, date ( "m/d", $v ['add_time'] ), $v ['junqu'], $v ['area'], $v ['man'], $v ['customer'], $v ['mobile_phone'], $v ['money'], $this->_status [$v ['status']] );
		}
	
	}
	
	public function listing() {
	}

}